import { useContext, useRef, useState, useEffect } from "react";
import { useXAgent, XStream } from "@ant-design/x";
import type { RequestData, MessageItem, Chat, Answer } from "./types";
import { MessageContext } from "../../App";
import {
  sendChatMessage,
  abortChat,
  translateText,
  saveProductMultilang,
  type ChatRequest,
  type SaveProductMultilangRequest,
} from "../../services/apiService";
import {
  createHumanInputMessage,
  HumanInputMessage,
} from "./stoppedOperations";
import { createAnswer, createAnswerSummary, createMessageItem } from "./utils";
import { useTranslation } from 'react-i18next';
import MarkdownIt, { Token } from 'markdown-it';

export const useChatAgent = (
  chatId: string,
  onHumanInputRequired?: (
    nodeId: string,
    nodeLabel: string,
    humanInputMessage: HumanInputMessage,
    nodeData: string,
  ) => void,
  onSummaryStreamUpdate?: (content: string) => void, // 新增：总结内容流式更新回调
) => {
  const abortController = useRef<AbortController>(null);
  const currentFlowId = useRef<string | null>(null); // 跟踪当前的flowid
  const currentRequestType = useRef<"chat" | "summary" | null>(null); // 跟踪请求类型
  const messageApi = useContext(MessageContext); // 直接使用上下文
  const { t, i18n } = useTranslation();

  // ==================== 统一 Token 管理系统 ====================

  // Token 管理器 - 统一处理所有类型的流式 token
  const tokenManager = {
    // 处理并发 WorkArea token
    handleConcurrentWorkAreaToken: async (
      data: any,
      answer: Answer,
      onUpdate: (data: any) => void,
      onSummaryStreamUpdate?: (content: string) => void
    ) => {
      const concurrentMatch = data.agentLabel.match(/^(W-.+)@(\d+)$/);
      if (!concurrentMatch) return false;

      const baseLabel = concurrentMatch[1];
      const blockIndex = parseInt(concurrentMatch[2]);

      // 初始化数据结构
      if (!answer.metadata[baseLabel]) {
        answer.metadata[baseLabel] = { blocks: {}, maxBlock: 0 };
      }

      // 保存中文原文到并发结构
      const originalKey = `${baseLabel}_original`;
      if (!answer.metadata[originalKey]) {
        answer.metadata[originalKey] = { blocks: {}, maxBlock: 0 };
      }
      if (!answer.metadata[originalKey].blocks[blockIndex]) {
        answer.metadata[originalKey].blocks[blockIndex] = "";
      }
      answer.metadata[originalKey].blocks[blockIndex] += data.data;
      answer.metadata[originalKey].maxBlock = Math.max(answer.metadata[originalKey].maxBlock, blockIndex);

      // 处理翻译逻辑
      if (i18n.language !== 'zh') {
        const bufferKey = `${baseLabel}@${blockIndex}`;
        if (!workAreaBuffers.current.has(bufferKey)) {
          workAreaBuffers.current.set(bufferKey, "");
        }

        const currentBuffer = workAreaBuffers.current.get(bufferKey) + data.data;
        workAreaBuffers.current.set(bufferKey, currentBuffer);

        if (containsSentenceEnd(data.data) && currentBuffer.trim()) {
          const translatedSentence = await translateIfNeeded(currentBuffer);
          if (!answer.metadata[baseLabel].blocks[blockIndex]) {
            answer.metadata[baseLabel].blocks[blockIndex] = "";
          }
          answer.metadata[baseLabel].blocks[blockIndex] += translatedSentence;
          workAreaBuffers.current.set(bufferKey, "");
        } else {
          return true; // 处理了但还在缓冲中
        }
      } else {
        if (!answer.metadata[baseLabel].blocks[blockIndex]) {
          answer.metadata[baseLabel].blocks[blockIndex] = "";
        }
        answer.metadata[baseLabel].blocks[blockIndex] += data.data;
      }

      answer.metadata[baseLabel].maxBlock = Math.max(answer.metadata[baseLabel].maxBlock, blockIndex);

      // 组合显示内容
      if (onSummaryStreamUpdate) {
        let combinedContent = "";
        for (let i = 0; i <= answer.metadata[baseLabel].maxBlock; i++) {
          if (answer.metadata[baseLabel].blocks[i]) {
            combinedContent += answer.metadata[baseLabel].blocks[i];
            if (i < answer.metadata[baseLabel].maxBlock) {
              combinedContent += "\n\n";
            }
          }
        }
        onSummaryStreamUpdate(combinedContent);
      }

      return true; // 已处理
    },

    // 处理普通 WorkArea token
    handleWorkAreaToken: async (
      data: any,
      answer: Answer,
      onUpdate: (data: any) => void,
      onSummaryStreamUpdate?: (content: string) => void
    ) => {
      // 先尝试并发处理
      const handled = await tokenManager.handleConcurrentWorkAreaToken(data, answer, onUpdate, onSummaryStreamUpdate);
      if (handled) {
        return true;
      }

      // 普通 WorkArea 处理
      if (answer.metadata[data.agentLabel] === undefined) {
        answer.metadata[data.agentLabel] = "";
      }

      // 保存中文原文
      const originalKey = `${data.agentLabel}_original`;
      if (answer.metadata[originalKey] === undefined) {
        answer.metadata[originalKey] = "";
      }
      answer.metadata[originalKey] += data.data;

      if (i18n.language !== 'zh') {
        const bufferKey = data.agentLabel;
        if (!workAreaBuffers.current.has(bufferKey)) {
          workAreaBuffers.current.set(bufferKey, "");
        }

        const currentBuffer = workAreaBuffers.current.get(bufferKey) + data.data;
        workAreaBuffers.current.set(bufferKey, currentBuffer);

        if (containsSentenceEnd(data.data) && currentBuffer.trim()) {
          const translatedSentence = await translateIfNeeded(currentBuffer);
          answer.metadata[data.agentLabel] += translatedSentence;
          workAreaBuffers.current.set(bufferKey, "");
          if (onSummaryStreamUpdate) {
            onSummaryStreamUpdate(answer.metadata[data.agentLabel]);
          }
        }
      } else {
        answer.metadata[data.agentLabel] += data.data;
        if (onSummaryStreamUpdate) {
          onSummaryStreamUpdate(answer.metadata[data.agentLabel]);
        }
      }

      return true;
    },

    // 处理 Copilot token
    handleCopilotToken: async (data: any, answer: Answer, messageItem: MessageItem, onUpdate: (data: any) => void) => {
      // 保存中文原文
      if (!answer.originalChinese) {
        answer.originalChinese = "";
      }
      answer.originalChinese += data.data;

      if (i18n.language !== 'zh') {
        sentenceBuffer.current += data.data;
        if (containsSentenceEnd(data.data) && sentenceBuffer.current.trim()) {
          const translatedSentence = await translateIfNeeded(sentenceBuffer.current);
          answer.display += translatedSentence;
          sentenceBuffer.current = "";
        }
      } else {
        answer.display += data.data;
      }
      onUpdate({ data: messageItem });
    },

    // 统一的 token 分发处理
    handleToken: async (
      data: any,
      context: {
        answer?: Answer,
        summary?: any,
        messageItem?: MessageItem,
        tokenType?: "summary" | "humanInput" | "question",
        humanInputMessage?: any
      },
      callbacks: {
        onUpdate?: (data: any) => void,
        onSummaryStreamUpdate?: (content: string) => void
      }
    ) => {
      if (!data.agentLabel) return false;

      // W- 标签处理（WorkArea）
      if (data.agentLabel.startsWith("W-")) {
        if (context.answer && callbacks.onSummaryStreamUpdate) {
          return await tokenManager.handleWorkAreaToken(
            data,
            context.answer,
            callbacks.onUpdate || (() => { }),
            callbacks.onSummaryStreamUpdate
          );
        }
        return false;
      }
      // C- 标签处理（Copilot）
      else if (data.agentLabel.startsWith("C-")) {
        if (context.answer && context.messageItem && context.tokenType === "question") {
          await tokenManager.handleCopilotToken(data, context.answer, context.messageItem, callbacks.onUpdate || (() => { }));
          return true;
        }
        return false;
      }

      return false;
    }
  };

  // ==================== 翻译管理系统 ====================

  // 创建 markdown-it 实例
  const md = useRef(new MarkdownIt());

  // 翻译缓存和状态管理
  const translationState = useRef({
    cache: new Map<string, string>(),
    sentenceBuffer: "",
    workAreaBuffers: new Map<string, string>(),
    abortController: null as AbortController | null,
  });

  // 监听语言切换，清理翻译缓存
  useEffect(() => {
    translationState.current.cache.clear();
  }, [i18n.language]);

  // ==================== 翻译管理系统 ====================
  const translationManager = {
    // 检查是否需要翻译
    shouldTranslate: () => i18n.language !== 'zh' && i18n.language !== 'th',

    // 获取目标语言
    getTargetLanguage: () => i18n.language === 'th' ? 'th' : 'en',

    // 检查是否为中文字符
    isChineseChar: (char: string) => /[\u4e00-\u9fff]/.test(char),

    // 检查是否为句子结束符
    isSentenceEnd: (char: string) => /[。！？；;!?]/.test(char),

    // 检查文本是否包含句子结束符（主要检查换行符和冒号）
    containsSentenceEnd: (text: string) => {
      // 如果包含图片链接，不应该触发句子结束
      if (/!\[.*?\]\(.*?\)/.test(text)) {
        return false;
      }
      // 主要依赖换行符来断句，同时也识别冒号（特别是在列表格式中）
      return /\n|：/.test(text);
    },

    // 检测是否包含 Markdown 格式
    containsMarkdownFormat: (text: string) => {
      try {
        const tokens = md.current.parse(text.trim(), {});
        const markdownTokenTypes = [
          'image', 'link_open', 'code_inline', 'code_block', 'fence',
          'heading_open', 'list_item_open', 'blockquote_open', 'table_open',
        ];
        return tokens.some(token => markdownTokenTypes.includes(token.type));
      } catch (error) {
        return false;
      }
    },

    // 创建缓存键
    createCacheKey: (text: string) => `${text.trim()}_${i18n.language}`,

    // 获取缓存的翻译
    getCachedTranslation: (text: string) => {
      const key = translationManager.createCacheKey(text);
      return translationState.current.cache.get(key);
    },

    // 设置翻译缓存
    setCachedTranslation: (text: string, translation: string) => {
      const key = translationManager.createCacheKey(text);
      translationState.current.cache.set(key, translation);
    },

    // 中止当前翻译请求
    abortCurrentTranslation: () => {
      if (translationState.current.abortController) {
        translationState.current.abortController.abort();
        translationState.current.abortController = null;
      }
    },

    // 清理所有缓冲区
    clearAllBuffers: () => {
      translationState.current.sentenceBuffer = "";
      translationState.current.workAreaBuffers.clear();
    },

    // 翻译纯文本（核心翻译函数，不处理特殊格式）
    translateTextCore: async (text: string): Promise<string> => {
      if (!text.trim() || !translationManager.shouldTranslate()) {
        return text;
      }

      // 如果只包含符号，直接返回不翻译
      if (translationManager.isSymbolOnlyText(text)) {
        return text;
      }

      // 检查缓存
      const cached = translationManager.getCachedTranslation(text);
      if (cached) {
        return cached;
      }

      try {
        // 中止之前的请求并创建新的
        translationManager.abortCurrentTranslation();
        translationState.current.abortController = new AbortController();

        const result = await translateText(
          text,
          "zh",
          translationManager.getTargetLanguage(),
          translationState.current.abortController.signal
        );

        const translatedText = result || text;
        translationManager.setCachedTranslation(text, translatedText);
        return translatedText;
      } catch (error) {
        if (error instanceof Error && error.name === 'AbortError') {
          return text;
        }
        console.warn("文本翻译失败，使用原文:", error);
        return text;
      }
    },

    // 翻译纯文本
    translateTextOnly: async (text: string): Promise<string> => {
      if (!text.trim() || !translationManager.shouldTranslate()) {
        return text;
      }

      // 如果只包含符号，直接返回不翻译
      if (translationManager.isSymbolOnlyText(text)) {
        return text;
      }

      // 如果包含 | 符号且不在递归调用中，使用表格单元格处理
      if (text.includes('|') && !text.includes('translateTextOnly_processing')) {
        return translationManager.translateTableCell(text);
      }

      // 如果包含图片格式，使用专门的图片处理函数
      if (translationManager.containsMarkdownImage(text)) {
        return translationManager.translateTextWithImages(text);
      }

      // 使用核心翻译函数
      return translationManager.translateTextCore(text);
    },

    // 检查文本是否包含 Markdown 图片格式
    containsMarkdownImage: (text: string) => /!\[.*?\]\(.*?\)/.test(text),

    // 检查文本是否只包含符号或表情符号（主要是 - 和 | 以及空格，以及各种表情符号）
    isSymbolOnlyText: (text: string) => {
      const trimmedText = text.trim();
      if (!trimmedText) return true;

      // 检查是否只包含符号字符 (-, |, :, 空格等)
      if (/^[\s\-|:]+$/.test(trimmedText)) return true;

      // 检查是否只包含表情符号
      // Unicode 表情符号范围：
      // \u{1F600}-\u{1F64F}: 表情符号 (Emoticons)
      // \u{1F300}-\u{1F5FF}: 杂项符号和象形文字 (Miscellaneous Symbols and Pictographs)
      // \u{1F680}-\u{1F6FF}: 交通和地图符号 (Transport and Map Symbols)
      // \u{2600}-\u{26FF}: 杂项符号 (Miscellaneous Symbols)
      // \u{2700}-\u{27BF}: 装饰符号 (Dingbats)
      // \u{1F900}-\u{1F9FF}: 补充符号和象形文字 (Supplemental Symbols and Pictographs)
      const emojiRegex = /^[\s\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F900}-\u{1F9FF}]+$/u;
      return emojiRegex.test(trimmedText);
    },

    // 专门处理包含图片的文本翻译
    translateTextWithImages: async (text: string): Promise<string> => {
      if (!translationManager.shouldTranslate() || !text.trim()) {
        return text;
      }

      // 如果只包含符号，直接返回不翻译
      if (translationManager.isSymbolOnlyText(text)) {
        return text;
      }

      // 如果包含 | 符号，按照表格处理逻辑（但避免无限循环）
      if (text.includes('|') && !text.match(/!\[.*?\]\(.*?\)/)) {
        return translationManager.translateTableCell(text);
      }

      // 如果不包含图片，使用普通翻译
      if (!translationManager.containsMarkdownImage(text)) {
        return translationManager.translateTextCore(text);
      }

      try {
        // 使用正则表达式分割文本，保留图片部分
        const imageRegex = /!\[.*?\]\(.*?\)/g;
        const parts = text.split(imageRegex);
        const images = text.match(imageRegex) || [];

        const translatedParts: string[] = [];

        for (let i = 0; i < parts.length; i++) {
          const part = parts[i];

          // 翻译非图片的文本部分
          if (part.trim() && translationManager.isChineseChar(part)) {
            const translated = await translationManager.translateTextCore(part);
            translatedParts.push(translated);
          } else {
            translatedParts.push(part);
          }

          // 添加对应的图片（如果存在）
          if (i < images.length) {
            translatedParts.push(images[i]);
          }
        }

        return translatedParts.join('');
      } catch (error) {
        console.warn("图片文本翻译失败，使用原文:", error);
        return text;
      }
    },

    // 专门处理表格单元格的翻译
    translateTableCell: async (text: string): Promise<string> => {
      if (!translationManager.shouldTranslate() || !text.trim()) {
        return text;
      }

      // 如果只包含符号，直接返回不翻译
      if (translationManager.isSymbolOnlyText(text)) {
        return text;
      }

      try {
        // 按照 | 分割文本
        const parts = text.split('|');
        const translatedParts: string[] = [];

        for (let i = 0; i < parts.length; i++) {
          const part = parts[i];

          // 如果是纯符号部分，不翻译
          if (translationManager.isSymbolOnlyText(part)) {
            translatedParts.push(part);
            continue;
          }

          // 如果包含中文，翻译
          if (part.trim() && translationManager.isChineseChar(part)) {
            // 保持前后空格
            const leadingSpace = part.match(/^(\s*)/)?.[1] || '';
            const trailingSpace = part.match(/(\s*)$/)?.[1] || '';
            const trimmedPart = part.trim();

            // 处理可能包含图片的文本
            let translated;
            if (translationManager.containsMarkdownImage(trimmedPart)) {
              // 对于包含图片的文本，直接在这里处理，避免循环调用
              const imageRegex = /!\[.*?\]\(.*?\)/g;
              const imageParts = trimmedPart.split(imageRegex);
              const images = trimmedPart.match(imageRegex) || [];

              const translatedImageParts: string[] = [];
              for (let k = 0; k < imageParts.length; k++) {
                const imagePart = imageParts[k];
                if (imagePart.trim() && translationManager.isChineseChar(imagePart)) {
                  const partTranslated = await translationManager.translateTextCore(imagePart);
                  translatedImageParts.push(partTranslated);
                } else {
                  translatedImageParts.push(imagePart);
                }
                if (k < images.length) {
                  translatedImageParts.push(images[k]);
                }
              }
              translated = translatedImageParts.join('');
            } else {
              translated = await translationManager.translateTextCore(trimmedPart);
            }

            translatedParts.push(leadingSpace + translated + trailingSpace);
          } else {
            translatedParts.push(part);
          }
        }

        return translatedParts.join('|');
      } catch (error) {
        console.warn("表格单元格翻译失败，使用原文:", error);
        return text;
      }
    },

    // 专门处理 Markdown 表格翻译
    translateMarkdownTable: async (text: string): Promise<string> => {
      if (!translationManager.shouldTranslate()) {
        return text;
      }

      try {
        // 按行分割文本
        const lines = text.split('\n');
        const translatedLines: string[] = [];

        for (let i = 0; i < lines.length; i++) {
          const line = lines[i];

          // 检查是否为表格分隔符行（如 | --- | --- |）
          if (/^\s*\|\s*[-:]+\s*(\|\s*[-:]+\s*)*\|\s*$/.test(line)) {
            // 这是表格分隔符行，直接保留不翻译
            translatedLines.push(line);
            continue;
          }

          // 检查是否为表格行（包含 | 符号）
          if (/^\s*\|.*\|\s*$/.test(line)) {
            // 这是表格行，使用专门的表格单元格翻译
            const translated = await translationManager.translateTableCell(line);
            translatedLines.push(translated);
          } else {
            // 不是表格行，使用支持图片的翻译
            if (line.trim()) {
              const translated = await translationManager.translateTextWithImages(line);
              translatedLines.push(translated);
            } else {
              translatedLines.push(line);
            }
          }
        }

        return translatedLines.join('\n');
      } catch (error) {
        console.warn("Markdown表格翻译失败，使用原文:", error);
        return text;
      }
    },

    // 翻译 Markdown 内容
    translateMarkdownText: async (text: string): Promise<string> => {
      if (!translationManager.shouldTranslate()) {
        return text;
      }

      // 检查是否包含表格
      if (/\|.*\|/.test(text) && (/\|\s*[-:]+\s*\|/.test(text) || text.split('\n').some(line => /^\s*\|.*\|\s*$/.test(line)))) {
        return translationManager.translateMarkdownTable(text);
      }

      try {
        const tokens = md.current.parse(text, {});
        const textNodes: any[] = [];

        // 收集文本节点
        tokens.forEach(token => {
          if (token.type === "inline" && token.children) {
            token.children.forEach(child => {
              if (child.type === "text") {
                textNodes.push(child);
              }
            });
          }
        });

        // 翻译文本节点
        for (const node of textNodes) {
          node.content = await translationManager.translateTextOnly(node.content);
        }

        return md.current.renderer.render(tokens, md.current.options, {});
      } catch (error) {
        console.warn("Markdown翻译失败，使用原文:", error);
        return text;
      }
    },

    // 统一翻译接口
    translate: async (text: string): Promise<string> => {
      if (!translationManager.shouldTranslate()) {
        return text;
      }

      // 按行分割并处理
      const lines = text.split(/(\n)/);
      const translatedLines: string[] = [];

      for (const line of lines) {
        if (line === '\n') {
          translatedLines.push(line);
        } else if (line.trim()) {
          const translated = translationManager.containsMarkdownFormat(line)
            ? await translationManager.translateMarkdownText(line)
            : await translationManager.translateTextOnly(line);
          translatedLines.push(translated);
        } else {
          translatedLines.push(line);
        }
      }

      return translatedLines.join('');
    },

    // 处理流式翻译（用于句子缓冲）
    processStreamingTranslation: async (
      data: string,
      bufferKey: string,
      onComplete: (translated: string) => void
    ) => {
      if (!translationManager.shouldTranslate()) {
        onComplete(data);
        return;
      }

      // 获取或创建缓冲区
      const currentBuffer = translationState.current.workAreaBuffers.get(bufferKey) || "";
      const newBuffer = currentBuffer + data;
      translationState.current.workAreaBuffers.set(bufferKey, newBuffer);

      // 检查是否需要翻译（包含句子结束符）
      if (translationManager.containsSentenceEnd(data) && newBuffer.trim()) {
        const translated = await translationManager.translate(newBuffer);
        onComplete(translated);
        translationState.current.workAreaBuffers.set(bufferKey, ""); // 清空缓冲区
      }
    },

    // 处理剩余缓冲区内容
    flushAllBuffers: async (onUpdate: (key: string, content: string) => void) => {
      if (!translationManager.shouldTranslate()) {
        return;
      }

      // 处理句子缓冲区
      if (translationState.current.sentenceBuffer.trim()) {
        const translated = await translationManager.translate(translationState.current.sentenceBuffer);
        onUpdate("sentence", translated);
        translationState.current.sentenceBuffer = "";
      }

      // 处理工作区缓冲区
      for (const [key, content] of translationState.current.workAreaBuffers.entries()) {
        if (content.trim()) {
          const translated = await translationManager.translate(content);
          onUpdate(key, translated);
        }
      }

      translationState.current.workAreaBuffers.clear();
    }
  };

  // 旧的函数保持兼容性，内部调用新的翻译管理器
  const isChineseChar = translationManager.isChineseChar;
  const isSentenceEnd = translationManager.isSentenceEnd;
  const containsSentenceEnd = translationManager.containsSentenceEnd;
  const containsMarkdownFormat = translationManager.containsMarkdownFormat;
  const containsMarkdownImage = translationManager.containsMarkdownImage;
  const isSymbolOnlyText = translationManager.isSymbolOnlyText;
  const translateTextOnly = translationManager.translateTextOnly;
  const translateTextWithImages = translationManager.translateTextWithImages;
  const translateTableCell = translationManager.translateTableCell;
  const translateMarkdownText = translationManager.translateMarkdownText;
  const translateIfNeeded = translationManager.translate;

  // 为兼容性保留旧的引用
  const sentenceBuffer = {
    get current() { return translationState.current.sentenceBuffer; },
    set current(value: string) { translationState.current.sentenceBuffer = value; }
  };
  const workAreaBuffers = {
    get current() { return translationState.current.workAreaBuffers; }
  };
  const translationAbortController = {
    get current() { return translationState.current.abortController; },
    set current(value: AbortController | null) { translationState.current.abortController = value; }
  };

  // 中止聊天的函数
  const abortChatHandler = async () => {
    try {
      // 中止翻译请求
      translationManager.abortCurrentTranslation();

      // 清空句子缓冲区
      translationManager.clearAllBuffers();

      // 根据请求类型调用相应的中止 API
      if (currentFlowId.current) {
        await abortChat(chatId, currentFlowId.current); // 传递flowid
        messageApi.success(
          `${currentRequestType.current === "summary" ? t('useChatAgent.summary') : t('useChatAgent.chat')}${t('useChatAgent.taskAborted')}`,
        );
      } else {
        await abortChat(chatId);
        messageApi.success(t('useChatAgent.taskAborted'));
      }
      const newChat = {
        ...chat,
        messageItems: chat.messageItems.map((item) => {
          item.answers.map((answer) => {
            if (answer.status === "pending")
              answer.status = "error";
          });
          return item;
        })
      }
      setChat(newChat);
    } catch (error) {
      console.error("Failed to abort chat:", error);
    }

    // 清空当前跟踪信息
    currentFlowId.current = null;
    currentRequestType.current = null;

    // 同时中止本地的 AbortController
    abortController.current?.abort();
  };

  // ==================== 请求配置管理 ====================

  // 统一的请求配置接口
  interface RequestConfig {
    flowId: string;
    requestType: "chat" | "summary";
    endpoint: "chat" | "summary";
    questionProcessor?: (question: string) => Promise<string>;
    contentProcessor?: (metadata: any) => any;
    streamProcessor?: (data: any, answer: Answer, messageItem: MessageItem) => Promise<void>;
  }

  // 请求配置工厂
  const createRequestConfig = async (requestType: string, metadata: any): Promise<RequestConfig> => {
    switch (requestType) {
      case "summary":
        const { SUMMARY_API_CONFIG } = await import("../../services/apiService");
        return {
          flowId: SUMMARY_API_CONFIG.FLOW_ID,
          requestType: "summary",
          endpoint: "summary",
          contentProcessor: (metadata) => {
            const { type: summaryType, content } = metadata;
            // 处理HTML内容，按天分割
            if (summaryType === "html") {
              const dayPattern = /(?=# 第\d+天)/g;
              const daySegments = content
                .split(dayPattern)
                .filter((segment: string) => segment.trim());
              return daySegments.length > 1 ? daySegments : [content];
            }
            return [content];
          }
        };

      case "humanInput":
      case "question":
      case "reask":
      default:
        const { CHAT_API_CONFIG } = await import("../../services/apiService");
        return {
          flowId: CHAT_API_CONFIG.FLOW_ID,
          requestType: "chat",
          endpoint: "chat",
          questionProcessor: async (question: string) => {
            // 统一的问题翻译处理
            if (i18n.language !== 'zh' && i18n.language !== 'th') {
              try {
                return (await translateText(
                  question,
                  i18n.language,
                  'zh',
                  translationState.current.abortController?.signal
                ))
              } catch (error) {
                console.warn("问题翻译失败，使用原文:", error);
                return question;
              }
            }
            return question;
          }
        };
    }
  };

  const [agent] = useXAgent({
    request: async (request: RequestData, { onUpdate, onSuccess, onError }) => {
      // 检查是否已有正在执行的请求
      if (currentFlowId.current && currentRequestType.current) {
        messageApi.warning(t('useChatAgent.taskInProgress'));
        // 正确处理错误状态，确保 agent 状态一致性
        onError(new Error(t('useChatAgent.taskInProgress')));
        return;
      }

      try {
        let messageItem = request.messageItem;
        const { question, type: requestType, answerId, metadata } = request;

        if (!messageItem) {
          messageItem = createMessageItem(question);
          onUpdate({ data: messageItem });
        }

        let answer: Answer;
        if (answerId) {
          answer = messageItem?.answers.find((ans) => ans.id === answerId) as Answer;
        } else {
          answer = createAnswer(messageItem);
        }

        if (!answer) {
          throw new Error("Answer not found in messageItem");
        }

        // 获取请求配置
        const config = await createRequestConfig(requestType, metadata);
        currentRequestType.current = config.requestType;
        currentFlowId.current = config.flowId;

        // 思维链时间计时系统
        const thinkTimers = new Map<string, number>();
        const thinkLabels = new Map<string, string>();
        const requestStartTime = Date.now();

        const appendThink = (message: string) => {
          answer.think += `\n${message}`;
        };

        const startThinking = (nodeId: string, nodeLabel: string, message: string) => {
          const timestamp = Date.now();
          thinkTimers.set(nodeId, timestamp);
          thinkLabels.set(nodeId, nodeLabel);
          answer.think += `\n${message}`;
        };

        const finishThinking = (nodeId: string, message: string) => {
          const endTime = Date.now();
          const startTime = thinkTimers.get(nodeId);
          const nodeLabel = thinkLabels.get(nodeId);

          if (startTime && nodeLabel) {
            const duration = (endTime - startTime) / 1000;
            const inProgressPattern = new RegExp(`\\n[\\t]*🤖 ${nodeLabel.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} ${t('useChatAgent.processing').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`);
            answer.think = answer.think.replace(inProgressPattern, '');
            answer.think += `\n${message} (${t('useChatAgent.duration')}: ${duration.toFixed(2)}s)`;
            thinkTimers.delete(nodeId);
            thinkLabels.delete(nodeId);
          } else {
            answer.think += `\n${message}`;
          }
        };

        const cancelThinking = (nodeId: string) => {
          const nodeLabel = thinkLabels.get(nodeId);
          if (nodeLabel) {
            const inProgressPattern = new RegExp(`\\n[\\t]*🤖 ${nodeLabel.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} ${t('useChatAgent.processing').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`);
            answer.think = answer.think.replace(inProgressPattern, '');
          }
          thinkTimers.delete(nodeId);
          thinkLabels.delete(nodeId);
        };

        // Summary 流处理函数
        const processSummaryStream = async (
          responseBody: ReadableStream,
          summary: any,
          messageItem: MessageItem,
          onUpdate: (data: any) => void,
          onSummaryStreamUpdate?: (content: string) => void
        ) => {
          let summaryContent = "";
          let summaryOriginalChinese = ""; // 存储中文原文
          let isInThinkSection = false;
          const summaryStartTime = Date.now();

          // 创建虚拟 answer 对象用于处理 WorkArea token
          const virtualAnswer: Answer = {
            messageItemId: messageItem.id,
            id: summary.id,
            display: "",
            originalChinese: "",
            think: "",
            metadata: {},
            humanInputs: [],
            summaries: [],
            status: "pending",
            date: new Date()
          };

          for await (const chunk of XStream({ readableStream: responseBody })) {
            if (!chunk.data) continue;
            try {
              const data = JSON.parse(chunk.data);
              if (data.event === "token" && data.data) {
                if (data.data.includes("<think>")) {
                  isInThinkSection = true;
                  summary.think += `\n${t('useChatAgent.startThinking')}\n`;
                }
                if (data.data.includes("</think>")) {
                  isInThinkSection = false;
                  summary.think += data.data + `\n${t('useChatAgent.endThinking')}`;
                  onUpdate({ data: messageItem });
                  continue;
                }

                if (isInThinkSection) {
                  summary.think += data.data;
                  onUpdate({ data: messageItem });
                } else {
                  // 使用统一的 token 管理器处理
                  if (data.agentLabel) {
                    // 处理 WorkArea token（包括并发）
                    const handled = await tokenManager.handleToken(
                      data,
                      {
                        answer: virtualAnswer,
                        messageItem: messageItem,
                        tokenType: "summary"
                      },
                      {
                        onUpdate: onUpdate,
                        onSummaryStreamUpdate: onSummaryStreamUpdate
                      }
                    );

                    // 如果是 WorkArea token，已经处理完毕
                    if (handled) {
                      continue;
                    }
                  }

                  // 处理普通 summary token
                  summaryOriginalChinese += data.data;

                  // 使用统一的翻译处理逻辑
                  await tokenManager.handleCopilotToken(
                    data,
                    virtualAnswer,
                    messageItem,
                    onUpdate
                  );

                  // 获取翻译后的内容用于流式更新
                  const currentContent = virtualAnswer.display;
                  if (onSummaryStreamUpdate) {
                    onSummaryStreamUpdate(currentContent);
                  }

                  // 同步 summaryContent 以便后续使用
                  summaryContent = currentContent;
                }
              }
            } catch {
              // 不是JSON就跳过
            }
          }

          // 处理剩余的缓冲区内容（现在由 tokenManager 统一处理）
          if (sentenceBuffer.current.trim() && i18n.language !== 'zh') {
            const translatedSentence = await translateIfNeeded(sentenceBuffer.current);
            virtualAnswer.display += translatedSentence;
            sentenceBuffer.current = "";
            summaryContent = virtualAnswer.display;
            if (onSummaryStreamUpdate) {
              onSummaryStreamUpdate(summaryContent);
            }
          }

          // 将 WorkArea 数据合并到 summary
          if (virtualAnswer.metadata["W-每日规划"]) {
            summary.metadata = summary.metadata || {};
            summary.metadata["W-每日规划"] = virtualAnswer.metadata["W-每日规划"];
            summary.metadata["W-每日规划_original"] = virtualAnswer.metadata["W-每日规划_original"];
          }

          // 合并其他 WorkArea 数据
          for (const [key, value] of Object.entries(virtualAnswer.metadata)) {
            if (key.startsWith("W-") && key !== "W-每日规划") {
              summary.metadata = summary.metadata || {};
              summary.metadata[key] = value;
            }
          }

          // 构建完整的总结内容，包含 WorkArea 数据
          let completeSummaryContent = summaryContent;
          let completeOriginalContent = summaryOriginalChinese;

          // 添加 WorkArea 内容到总结中
          if (virtualAnswer.metadata["W-每日规划"]) {
            if (virtualAnswer.metadata["W-每日规划"].blocks) {
              // 并发结构
              let workAreaContent = "";
              let workAreaOriginal = "";
              for (let i = 0; i <= virtualAnswer.metadata["W-每日规划"].maxBlock; i++) {
                if (virtualAnswer.metadata["W-每日规划"].blocks[i]) {
                  workAreaContent += virtualAnswer.metadata["W-每日规划"].blocks[i] + '\n';
                }
                if (virtualAnswer.metadata["W-每日规划_original"]?.blocks[i]) {
                  workAreaOriginal += virtualAnswer.metadata["W-每日规划_original"].blocks[i] + '\n';
                }
              }
              completeSummaryContent += '\n\n' + workAreaContent;
              completeOriginalContent += '\n\n' + workAreaOriginal;
            } else {
              // 普通结构
              completeSummaryContent += '\n\n' + virtualAnswer.metadata["W-每日规划"];
              if (virtualAnswer.metadata["W-每日规划_original"]) {
                completeOriginalContent += '\n\n' + virtualAnswer.metadata["W-每日规划_original"];
              }
            }
          }

          // 添加其他 WorkArea 内容
          for (const [key, value] of Object.entries(virtualAnswer.metadata)) {
            if (key.startsWith("W-") && !key.endsWith("_original") && key !== "W-每日规划" && typeof value === 'string') {
              completeSummaryContent += '\n\n' + value;
              const originalKey = `${key}_original`;
              if (virtualAnswer.metadata[originalKey]) {
                completeOriginalContent += '\n\n' + virtualAnswer.metadata[originalKey];
              }
            }
          }

          summary.display = completeSummaryContent; // 显示对应语言的内容
          summary.originalChinese = completeOriginalContent; // 存储中文原文
          onUpdate({ data: messageItem });
        };

        // 辅助函数：添加 Flow HTML 内容
        const addFlowHtmlContent = (answer: Answer) => {
          if (answer.metadata["W-每日规划"]) {
            let str = '';
            if (answer.metadata["W-每日规划"].blocks) {
              for (let i = 0; i <= answer.metadata["W-每日规划"].maxBlock; i++) {
                if (answer.metadata["W-每日规划"].blocks[i]) {
                  str += answer.metadata["W-每日规划"].blocks[i] + '\n';
                }
              }
            } else {
              str = answer.metadata["W-每日规划"];
            }
            answer.display += '<flow_html>' + str + '</flow_html>';
          }
          if (answer.metadata["W-其他城市旅游规划"]) {
            answer.display += `<flow_html>${answer.metadata["W-其他城市旅游规划"]}</flow_html>`;
          }
          if (answer.metadata["W-其他回答"]) {
            answer.display += `<flow_html>${answer.metadata["W-其他回答"]}</flow_html>`;
          }
          if (answer.metadata["W-Output"]) {
            answer.display += `<flow_html>${answer.metadata["W-Output"]}</flow_html>`;
          }
        };

        // Chat 流处理函数
        const processChatStream = async (
          responseBody: ReadableStream,
          answer: Answer,
          messageItem: MessageItem,
          onUpdate: (data: any) => void,
          onSummaryStreamUpdate: ((content: string) => void) | undefined,
          metadata: any
        ) => {
          let agentFlowLevel = 0;
          let tokenType: "summary" | "humanInput" | "question" = "question";
          const humanInputMessage = createHumanInputMessage("proceed", "", "", answer.id, messageItem.id, "");

          for await (const chunk of XStream({ readableStream: responseBody })) {
            if (!chunk.data) continue;
            try {
              const data = JSON.parse(chunk.data);

              // 流式 token 处理
              if (data.event === "token" && data.data) {
                if (data.agentLabel) {
                  if (tokenType === "humanInput") {
                    if (data.agentLabel?.startsWith('Q-') && i18n.language !== 'zh') {
                      humanInputMessage.AIQuestion += await translateText(data.data, 'zh', i18n.language);
                    }
                    else {
                      humanInputMessage.AIQuestion += data.data;
                    }
                  }
                  // 使用统一的 token 管理器处理
                  const handled = await tokenManager.handleToken(
                    data,
                    {
                      answer: answer,
                      messageItem: messageItem,
                      tokenType: tokenType,
                      humanInputMessage: humanInputMessage
                    },
                    {
                      onUpdate: onUpdate,
                      onSummaryStreamUpdate: onSummaryStreamUpdate
                    }
                  );

                  if (handled) {
                    continue;
                  }

                  onUpdate({ data: messageItem });
                }
              }

              // 错误处理
              if (data.event === "error" && (data.data.includes("Request was aborted.") || data.data.includes("AbortError"))) {
                appendThink(t('useChatAgent.interruptedByUser'));
              }

              // Agent Flow 事件处理
              if (data.event === "agentFlowEvent") {
                if (data.data === "FINISHED" || data.data === "ERROR") agentFlowLevel--;
                if (data.data === "INPROGRESS") agentFlowLevel++;
              }

              // 节点状态处理
              if (data.event === "nextAgentFlow") {
                const tabStr = "\t".repeat(agentFlowLevel);

                if (data.data.status === "INPROGRESS") {
                  const translatedLabel = await translateIfNeeded(data.data.nodeLabel);
                  startThinking(data.data.nodeId, translatedLabel, `${tabStr}🤖 ${translatedLabel} ${t('useChatAgent.processing')}`);
                }
                if (data.data.status === "FINISHED") {
                  const translatedLabel = await translateIfNeeded(data.data.nodeLabel);
                  finishThinking(data.data.nodeId, `${tabStr}✅ ${translatedLabel} ${t('useChatAgent.completed')}`);
                }
                if (data.data.status === "ERROR") {
                  const translatedLabel = await translateIfNeeded(data.data.nodeLabel);
                  finishThinking(data.data.nodeId, `${tabStr}❌ ${translatedLabel} ${t('useChatAgent.failed')}`);
                }
                if (data.data.status === "STOPPED") {
                  cancelThinking(data.data.nodeId);
                }
                onUpdate({ data: messageItem });
              }

              // Human Input 处理
              if (data.event === "nextAgentFlow" && data.data.nodeId.startsWith("humanInputAgentflow")) {
                if (data.data.status === "STOPPED") {
                  tokenType = "question";
                  if (onHumanInputRequired) {
                    humanInputMessage.data = {
                      action: "proceed",
                      nodeId: data.data.nodeId,
                      nodeLabel: data.data.nodeLabel,
                      feedback: processedQuestion,
                    };
                    onHumanInputRequired(data.data.nodeId, data.data.nodeLabel, humanInputMessage, data.data);
                  }
                }
                if (data.data.status === "FINISHED") {
                  tokenType = "question";
                  if (metadata.flightInfo) {
                    answer.metadata.flightInfo = metadata.flightInfo;
                    answer.metadata.flightList = metadata.flightList;
                  }
                }
                if (data.data.status === "INPROGRESS") {
                  tokenType = "humanInput";
                }
              }

              // 请求完成处理
              if (agentFlowLevel === 0 && data.event === "end") {
                answer.status = "completed";
                const totalDuration = (Date.now() - requestStartTime) / 1000;
                appendThink(`✅✅✅ ${t('useChatAgent.responseCompleted')} (${t('useChatAgent.totalTime')}: ${totalDuration.toFixed(2)}s)`);

                // 处理剩余缓冲区
                await translationManager.flushAllBuffers((key: string, content: string) => {
                  if (key === "sentence") {
                    answer.display += content;
                    onUpdate({ data: messageItem });
                  } else {
                    // 使用 tokenManager 处理剩余的 WorkArea 内容
                    const fakeData = { agentLabel: key, data: content };
                    tokenManager.handleWorkAreaToken(fakeData, answer, onUpdate, onSummaryStreamUpdate);
                  }
                });
              }
            } catch {
              // 不是JSON就跳过
            }
          }

          // 添加 flow_html 内容
          addFlowHtmlContent(answer);
        };

        // 处理取消操作
        if (requestType === "humanInput" && metadata.action === "cancel") {
          appendThink(t('useChatAgent.operationCancelled'));
          answer.status = "error";

          // 清理状态，确保下次可以正常发送消息
          currentFlowId.current = null;
          currentRequestType.current = null;

          onError(new Error(t('useChatAgent.userCancelled')));
          return;
        }

        // 统一的请求体构建
        let requestBody: any;
        let processedQuestion = question;

        if (config.endpoint === "summary") {
          // Summary 请求特殊处理
          const summary = createAnswerSummary(answer.id, messageItem.id);
          answer.summaries.push(summary);
          onUpdate({ data: messageItem });

          const { type: summaryType } = metadata;
          let processedContent = config.contentProcessor ? config.contentProcessor(metadata) : [metadata.content];

          // 如果传入的是翻译后的内容，尝试使用中文原文
          if (summaryType === "html") {
            // 构建中文原文内容
            let chineseContent = "";

            // 从 WorkArea 的原文数据中重建内容
            if (answer.metadata["W-每日规划_original"]) {
              const originalBlocks = answer.metadata["W-每日规划_original"];
              for (let i = 0; i <= originalBlocks.maxBlock; i++) {
                if (originalBlocks.blocks[i]) {
                  chineseContent += originalBlocks.blocks[i] + '\n';
                }
              }
            }

            // 添加其他 WorkArea 的原文
            for (const [key, value] of Object.entries(answer.metadata)) {
              if (key.endsWith('_original') && key !== "W-每日规划_original" && typeof value === 'string') {
                chineseContent += value;
              }
            }

            // 如果有其他中文原文，也添加进去
            if (answer.originalChinese && !chineseContent.includes(answer.originalChinese)) {
              chineseContent += answer.originalChinese;
            }

            // 如果构建了中文原文，使用它；否则使用原来的内容
            if (chineseContent.trim()) {
              processedContent = config.contentProcessor ? config.contentProcessor({
                ...metadata,
                content: chineseContent
              }) : [chineseContent];
            }
          }

          // 使用总结API
          const { sendSummaryRequest } = await import("../../services/apiService");
          const response = await sendSummaryRequest(
            {
              content: processedContent,
              contentType: summaryType as "product" | "html",
              chatId: chatId,
            },
            abortController.current?.signal,
          );

          if (!response.body) throw new Error("No stream");

          // 处理 Summary 流式响应
          try {
            await processSummaryStream(response.body, summary, messageItem, onUpdate, onSummaryStreamUpdate);
          } finally {
            // 确保状态清理，即使处理过程中出现异常
            currentFlowId.current = null;
            currentRequestType.current = null;
          }

          answer.status = "completed";
          onSuccess([{ data: messageItem }]);
          return;
        } else {
          // Chat 请求处理 - 统一在这里处理问题翻译
          if (config.questionProcessor) {
            processedQuestion = await config.questionProcessor(processedQuestion);
          }

          // 构建请求体
          if (requestType === "humanInput") {
            const humanInputMessage = createHumanInputMessage("proceed", "", "", answer.id, messageItem.id, "");
            answer.humanInputs.push(humanInputMessage);
            onUpdate({ data: messageItem });

            requestBody = {
              question: processedQuestion,
              chatId: chatId,
              humanInput: {
                type: metadata.action,
                startNodeId: metadata.nodeId,
                feedback: processedQuestion,
              },
              streaming: true,
            };
          } else {
            // question, reask 等请求 - 直接使用已翻译的问题，避免双重翻译
            const finalQuestion = requestType === "reask" ? messageItem.question : processedQuestion;

            requestBody = {
              question: finalQuestion,
              chatId: chatId,
              overrideConfig: {},
              streaming: true,
            };
          }

          const response = await sendChatMessage(requestBody, abortController.current?.signal);
          if (!response.body) throw new Error("No stream");

          // 处理 Chat 流式响应
          try {
            await processChatStream(response.body, answer, messageItem, onUpdate, onSummaryStreamUpdate, metadata);
          } finally {
            // 确保状态清理，即使处理过程中出现异常
            currentFlowId.current = null;
            currentRequestType.current = null;
          }
        }

        // answer.status = "completed";
        onSuccess([{ data: messageItem }]);

        // 清理flowid信息
        currentFlowId.current = null;
        currentRequestType.current = null;
      } catch (err) {
        // 清理翻译相关状态
        translationManager.abortCurrentTranslation();
        translationManager.clearAllBuffers();

        // 清理flowid信息
        currentFlowId.current = null;
        currentRequestType.current = null;

        onError(err instanceof Error ? err : new Error(String(err)));
      }
    },
  });

  const loading = agent.isRequesting();

  const [chat, setChat] = useState<Chat>({
    chatId,
    userId: "",
    messageItems: [],
    metadata: {},
  });

  const onRequest = (
    request: RequestData,
    messageItemId?: string,
    callbacks?: (data: MessageItem) => void
  ) => {
    request.messageItem = chat.messageItems?.find(
      (item) => item.id === messageItemId,
    );
    agent.request(request, {
      onUpdate: (chunk) => {
        const updateItem = chunk.data;
        setChat((prev) => {
          let newItems = prev.messageItems.map((item) =>
            item.id === updateItem.id ? updateItem : item,
          );
          if (!newItems.find((item) => item.id === updateItem.id)) {
            newItems = [...newItems, updateItem];
          }
          return { ...prev, messageItems: newItems };
        });
      },

      onSuccess: (data) => {
        const updateItem = data[0] as MessageItem;
        setChat((prev) => {
          const newItems = prev.messageItems.map((item) =>
            item.id === updateItem.id ? updateItem : item,
          );
          return { ...prev, messageItems: newItems };
        });
        const foundItem = chat.messageItems.find(f => f.id === messageItemId);
        if (messageItemId && foundItem) {
          callbacks?.(foundItem);
        }
      },

      onError: function (error: Error): void {
        setChat((prev) => ({ ...prev, error: error.message }));
        console.error("Request error:", error);
      },
    });
  };

  return {
    chat,
    onRequest,
    setChat,
    loading,
    abortController,
    abortChat: abortChatHandler,
  };
};
